import React, { useEffect } from 'react';
import { Form, Input } from 'antd';
import Modal from '@/components/Modal';
import './index.less';

const { Item: FormItem } = Form;

interface CreateCateModalProps {
  visible?: boolean;
  data?: CateItem;
  onCancel?: () => void;
  onOk?: (val: CateItem) => void;
}

const CreateCateModal: React.FC<CreateCateModalProps> = ({
  visible = false,
  data,
  onCancel,
  onOk,
}) => {
  const [form] = Form.useForm();
  const { id } = data || {};

  const submit = () => {
    form.validateFields().then((res) => {
      const params = { ...data, ...res };
      onOk && onOk(params);
    });
  };

  const cancel = () => {
    onCancel && onCancel();
  };

  useEffect(() => {
    if (!visible) {
      form?.resetFields();
    } else if (data) {
      form.setFieldsValue(data);
    }
  }, [visible]);

  return (
    <Modal
      width={400}
      title={!id ? '新增分类' : '修改分类'}
      visible={visible}
      onCancel={cancel}
      onOk={submit}
      className="create-cate-modal"
    >
      <Form form={form}>
        <FormItem
          label="分类名称"
          name="name"
          rules={[
            { required: true, message: '请输入分类名称', whitespace: true },
          ]}
        >
          <Input placeholder="请输入分类名称" />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default React.memo(CreateCateModal);
